import React, { Suspense } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import { routes } from './routes';
import AuthGuard from './AuthGuard';

// 加载指示器
const LoadingFallback = () => <div>页面加载中...</div>;

// 递归渲染路由
const renderRoutes = (routes) => {
  return routes.map((route) => {
    if (route.children) {
      return (
        <Route
          key={route.path}
          path={route.path}
          element={
            <AuthGuard requiresAuth={route.meta?.requiresAuth}>
              <Suspense fallback={<LoadingFallback />}>
                <route.component />
              </Suspense>
            </AuthGuard>
          }
        >
          {renderRoutes(route.children)}
        </Route>
      );
    }
    
    return (
      <Route
        key={route.path}
        path={route.path}
        element={
          <AuthGuard requiresAuth={route.meta?.requiresAuth}>
            <Suspense fallback={<LoadingFallback />}>
              <route.component />
            </Suspense>
          </AuthGuard>
        }
      />
    );
  });
};

// 路由组件
const AppRouter = () => {
  return (
    <Routes>
      {renderRoutes(routes)}
      {/* 默认路由重定向 */}
      <Route path="/" element={<Navigate to="/dashboard" replace />} />
      {/* 未匹配路由重定向到404 */}
      <Route path="*" element={<Navigate to="/404" replace />} />
    </Routes>
  );
};

export default AppRouter;